package com.iwhalecloud.bss.kite.cucc.web.controller.reception;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.dto.ContextDTO;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICuccLoginService;
import com.iwhalecloud.bss.kite.cucc.client.api.reception.ICustReceptionService;
import com.iwhalecloud.bss.kite.cucc.client.api.session.ICuccSessionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.cust.CuccContextCustDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.inf.req.NoticeExitReqDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.inf.rsp.NoticeExitRspDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.login.auth.CuccAuthLoginInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.login.auth.CuccAuthUserInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.order.KiteCustomerInfoReq;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.scene.CuccCustInfoDetailDTO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.LocalCustInfoVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.TransferTargetCustVO;
import com.iwhalecloud.bss.kite.cucc.manager.scene.service.operate.LocalOperateOfferInstContractRelService;
import com.iwhalecloud.bss.kite.cucc.service.cache.CuccContextCustCache;
import com.iwhalecloud.bss.kite.cucc.service.cache.CuccCustInfoDetailCache;
import com.iwhalecloud.bss.kite.cucc.service.util.CustInfoUtils;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInstContract;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.transaction.TransactionContext;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.ztesoft.bss.base.annotation.IgnoreSession;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 *
 */
@RestController
@RequestMapping("/localReception")
@Api(tags = {"/localReception - 定制包客户接待展示页"})
public class LocalCustReceptionController {

    @Autowired
    private ICustReceptionService custReceptionService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private LocalOperateOfferInstContractRelService operateOfferInstContractRelService;

    @ApiOperation(value = "初始化上下文", notes = "初始化上下文，受理时初始化上下文")
    @GetMapping("initContext")
    public DataResult<CuccCustInfoDetailDTO> initContext(@RequestParam String custId, @RequestParam(required = false) String custState) {
        if (KiteStringUtils.isEmpty(custId)) {
            return ErrorConsts.SUCCESS.getResult(null);
        }
        String provinceNbr = ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr();
        CuccContextCustDTO contextCust = CustInfoUtils.getCustInfo(custId, provinceNbr, custState);
        KiteWebContext.initContext(KiteWebContext.getKiteContextId(), contextCust);

        CuccContextCustCache.put(ContextUtil.getLoginInfo().getUserInfo().getUserCode(), custId, contextCust);
        return ErrorConsts.SUCCESS.getResult(CuccCustInfoDetailCache.get(custId));
    }

    @ApiOperation(value = "初始化上下文", notes = "初始化上下文，收入归集集团批量导入")
    @GetMapping("initTempCustContext")
    public DataResult<CuccCustInfoDetailDTO> initTempCustContext(@RequestParam String custId, @RequestParam(required = false) String custState) {
        if (KiteStringUtils.isEmpty(custId)) {
            return ErrorConsts.SUCCESS.getResult(null);
        }
        CuccContextCustDTO contextCust = new CuccContextCustDTO();
        CuccCustInfoDetailDTO custInfoDetail = new CuccCustInfoDetailDTO();
        contextCust.setCustId(custId);
        contextCust.setCustName("收入归集集团临时客户");
        contextCust.setCustState(custState);
        custInfoDetail.setCustId(custId);
        custInfoDetail.setCustName("收入归集集团临时客户");
        custInfoDetail.setCustState(custState);
        CuccContextCustCache.put(ContextUtil.getLoginInfo().getUserInfo().getUserCode(), custId, contextCust);
        CuccCustInfoDetailCache.put(custId, custInfoDetail);
        KiteWebContext.initContext(KiteWebContext.getKiteContextId(), contextCust);
        return ErrorConsts.SUCCESS.getResult(custInfoDetail);
    }

    @ApiOperation(value = "获取上下文", notes = "获取上下文")
    @ApiImplicitParams({@ApiImplicitParam(name = "key", value = "缓存key", required = true)})
    @GetMapping("getContext")
    public DataResult<ContextDTO> getContext(@RequestParam String key) {
        return ErrorConsts.SUCCESS.getResult(KiteWebContext.getContext());
    }

    @ApiOperation(value = "查询服务提供")
    @ApiImplicitParams({@ApiImplicitParam(name = "offerId", value = "销售品标识", required = true)
    })
    @GetMapping(value = "serviceOfferId")
    public DataResult<String> getServiceOfferId(@RequestParam String offerId) {
        //return serviceOfferService.getServiceOfferId(offerId);
        return null;
    }

    @ApiOperation(value = "查询客户列表", notes = "查询客户列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "pageNum", value = "第几页", required = false),
        @ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false)
    })
    @PostMapping("/queryCustomerList")
    public DataResult<PageInfo<CuccCustInfoDTO>> queryCustomerList(@RequestBody KiteCustomerInfoReq kiteCustomerInfoReq,
        @RequestParam(required = false) Integer pageNum, @RequestParam(required = false) Integer pageSize) {
        kiteCustomerInfoReq.setProvinceCode(ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
        kiteCustomerInfoReq.setEparchyCode(ContextUtil.getSimpleLoginInfo().getLanId());
        kiteCustomerInfoReq.setStaffCode(ContextUtil.getSimpleLoginInfo().getStaffCode());
        kiteCustomerInfoReq.setPageNum(pageNum);
        kiteCustomerInfoReq.setPageSize(pageSize);
        PageInfo<CuccCustInfoDTO> list = custReceptionService.customerListQuery(kiteCustomerInfoReq);
        return ErrorConsts.SUCCESS.getResult(list);
    }


    @ApiOperation(value = "查询客户信息")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "sceneInstId", value = "场景实例Id", required = false)
    })
    @GetMapping(value = "/getCustInfo")
    public DataResult<List<LocalCustInfoVO>> getCustInfo(String sceneInstId) {
        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        LocalCustInfoVO localCustInfoVO = custReceptionService.getCustInfoBySceneInstId(sceneInstId);
        List<LocalCustInfoVO >localCustInfoList = new ArrayList<>();
        localCustInfoList.add(localCustInfoVO);
        return ErrorConsts.SUCCESS.getResult(localCustInfoList);
    }

    @ApiOperation(value = "过户-查询客户详情")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "custId", value = "客户Id", required = false)
    })
    @GetMapping(value = "/getCustomerDetail")
    public DataResult<List<LocalCustInfoVO>> getCustomerDetail(String custId, String sceneInstId) {
        Map<String, String> custInfo = new HashMap<>();
        custInfo.put("provinceCode", ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
        custInfo.put("eparchyCode", ContextUtil.getSimpleLoginInfo().getLanId());
        custInfo.put("staffCode", ContextUtil.getSimpleLoginInfo().getStaffCode());
        custInfo.put("custId", custId);
        LocalCustInfoVO localCustInfoVO = custReceptionService.getCustomerDetailToChange(custInfo, sceneInstId);
        List<LocalCustInfoVO> localCustInfoList = new ArrayList<>();
        localCustInfoList.add(localCustInfoVO);
        return ErrorConsts.SUCCESS.getResult(localCustInfoList);
    }

    @ApiOperation(value = "运营平台登录", notes = "运营平台登录")
    @ApiImplicitParams({@ApiImplicitParam(name = "sessionId", value = "SessionId", required = true)})
    @GetMapping("/pretendLogin")
    public DataResult<CuccAuthUserInfoDTO> pretendLogin(@RequestParam String sessionId) {
        ContextUtil.setHttpSessoinId(sessionId);
        CuccAuthLoginInfoDTO loginInfo = custReceptionService.pretendLogin(sessionId);
        //设置登录信息
        SpringUtil.getBean(ICuccLoginService.class).saveLoginInfoFromPortal(sessionId, loginInfo);
        return ErrorConsts.SUCCESS.getResult(loginInfo.getUserInfo());
    }

    @ApiOperation(value = "运营平台退出", notes = "运营平台退出")
    @ApiImplicitParams({@ApiImplicitParam(name = "noticeExitReqDTO", value = "noticeExitReqDTO", required = true)})
    @PostMapping("/pretendLogout")
    public DataResult<NoticeExitRspDTO> pretendLogout(@RequestBody NoticeExitReqDTO noticeExitReqDTO) {
        ICuccSessionService cuccSessionService = SpringUtil.getBean(ICuccSessionService.class);
        return ErrorConsts.SUCCESS.getResult(cuccSessionService.expirySessionInfo(noticeExitReqDTO));
    }

    @IgnoreSession
    @ApiOperation(value = "登录", notes = "登录（从订单中心登录）")
    @ApiImplicitParams({@ApiImplicitParam(name = "sessionId", value = "SessionId", required = true)})
    @GetMapping("/pretendLoginFromOrder")
    public DataResult<Boolean> pretendLoginFromOrder(@RequestParam String sessionId) {
        ContextUtil.setHttpSessoinId(sessionId);
        return custReceptionService.pretendLoginFromOrder(sessionId);
    }


    @ApiOperation(value = "(新)查询客户列表", notes = "(新)查询客户列表")
    @PostMapping("/queryCustomerListNew")
    public DataResult<PageInfo<CuccCustInfoDTO>> queryCustomerListNew(@RequestBody KiteCustomerInfoReq kiteCustomerInfoReq) {
        if(KiteStringUtils.isEmpty(kiteCustomerInfoReq.getProvinceCode())){
            kiteCustomerInfoReq.setProvinceCode(ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
        }
        if(KiteStringUtils.isEmpty(kiteCustomerInfoReq.getEparchyCode())){
            kiteCustomerInfoReq.setEparchyCode(ContextUtil.getLoginInfo().getUserInfo().getPostLanId());
        }
//        if(KiteStringUtils.isEmpty(kiteCustomerInfoReq.getIntProvinceCode())){
//            //国际业务云联网需求，通过组织结构下的proviceCode来判断接口调用
//            kiteCustomerInfoReq.setIntProvinceCode(ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
//        }
        //
//        PageInfo<CuccCustInfoDTO> list=null;
//        if(!KiteStringUtils.isEmpty(kiteCustomerInfoReq.getIntProvinceCode())&&kiteCustomerInfoReq.getIntProvinceCode().startsWith("48")||kiteCustomerInfoReq.getIntProvinceCode().startsWith("49")){
//            list= custReceptionService.customerListQueryNewForNational(kiteCustomerInfoReq);
//        }else {
        PageInfo<CuccCustInfoDTO>  list = custReceptionService.customerListQueryNew(kiteCustomerInfoReq);

        return ErrorConsts.SUCCESS.getResult(list);
    }

    @ApiOperation(value = "(新)查询客户信息", notes = "(新)查询客户信息")
    @PostMapping("/getCustomerInfoNew")
    public DataResult<CuccCustInfoDetailDTO> getCustomerInfoNew(@RequestParam String custId) {
        CuccCustInfoDetailDTO dto = custReceptionService.getCustomerInfoNew(custId);
        return ErrorConsts.SUCCESS.getResult(dto);
    }

    @ApiOperation(value = "查询过户目标客户列表", notes = "查询过户目标客户列表")
    @PostMapping("/queryCustomerListTransfer")
    public DataResult<PageInfo<CuccCustInfoDTO>> queryCustomerTransferList(@RequestBody KiteCustomerInfoReq kiteCustomerInfoReq) {
        if (KiteStringUtils.isEmpty(kiteCustomerInfoReq.getProvinceCode())) {
            kiteCustomerInfoReq.setProvinceCode(ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
        }
        if (KiteStringUtils.isEmpty(kiteCustomerInfoReq.getEparchyCode())) {
            kiteCustomerInfoReq.setEparchyCode(ContextUtil.getLoginInfo().getUserInfo().getPostLanId());
        }
        PageInfo<CuccCustInfoDTO> list = custReceptionService.queryCustomerTransferList(kiteCustomerInfoReq);
        return ErrorConsts.SUCCESS.getResult(list);
    }

    @ApiOperation(value = "保存过户目标客户实例", notes = "保存过户目标客户实例")
    @PostMapping("/addTransferCustInst")
    public DataResult<CuccCustInfoDetailDTO> addTransferCustInst(@RequestBody TransferTargetCustVO transferTargetCustVO,
                                                                 @RequestParam String sceneInstId) {
        if (KiteStringUtils.isEmpty(sceneInstId)) {
            sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        }
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String newCustId = transferTargetCustVO.getCustId();
        kiteSceneInst.setNewCustId(newCustId);

        TransactionContext.getContainer().putSceneInst(kiteSceneInst);
        CuccCustInfoDetailDTO cuccCustInfoDetailDTO = custReceptionService.getCustomerInfoNew(newCustId);
        CuccCustInfoDTO cuccCustInfoDTO = new CuccCustInfoDTO();
        cuccCustInfoDTO.setAddress(cuccCustInfoDetailDTO.getAddress());
        cuccCustInfoDTO.setEparchyName(cuccCustInfoDetailDTO.getEparchyName());
        cuccCustInfoDTO.setCustName(cuccCustInfoDetailDTO.getCustName());
        cuccCustInfoDTO.setCustState("0");
        cuccCustInfoDTO.setCustType(cuccCustInfoDetailDTO.getCustClassType());
        cuccCustInfoDTO.setProvinceCode(cuccCustInfoDetailDTO.getProvinceCode());
        cuccCustInfoDTO.setAddr(cuccCustInfoDetailDTO.getAddress());
        cuccCustInfoDTO.setBbssCustId(cuccCustInfoDetailDTO.getBbssCustId());
        cuccCustInfoDTO.setCustId(cuccCustInfoDetailDTO.getCustId());
        cuccCustInfoDTO.setContactName(cuccCustInfoDetailDTO.getContactName());
        cuccCustInfoDTO.setGroupId(cuccCustInfoDetailDTO.getGroupId());
        cuccCustInfoDTO.setEparchyCity(cuccCustInfoDetailDTO.getEparchyCode());
        cuccCustInfoDTO.setEparchyArea(cuccCustInfoDetailDTO.getBcityCode());
        cuccCustInfoDTO.setCertiCode(cuccCustInfoDetailDTO.getCertiCode());
        cuccCustInfoDTO.setCertiTypeCode(cuccCustInfoDetailDTO.getCertiTypeCode());

        if (Objects.nonNull(cuccCustInfoDTO)) {
            operateSceneInstService
                .putExtParameter(sceneInstId, sceneInstId + "_transNewCustDTO", cuccCustInfoDTO);
        }
        operateSceneInstService.putExtParameter(sceneInstId, "addTransferCustInst", transferTargetCustVO);

        Map addTransferCustInstInfo = new HashMap();
        addTransferCustInstInfo.put("custId", transferTargetCustVO.getCustId());
        addTransferCustInstInfo.put("custName", transferTargetCustVO.getCustName());
        addTransferCustInstInfo.put("oldCustId", transferTargetCustVO.getOldCustId());
        addTransferCustInstInfo.put("certTypeCode", transferTargetCustVO.getCertTypeCode());
        addTransferCustInstInfo.put("certCode", transferTargetCustVO.getCertCode());
        addTransferCustInstInfo.put("groupId", transferTargetCustVO.getGroupId());
        addTransferCustInstInfo.put("provinceCode", transferTargetCustVO.getProvinceCode());
        addTransferCustInstInfo.put("eparchyCode", transferTargetCustVO.getEparchyCode());
        addTransferCustInstInfo.put("eparchyName", transferTargetCustVO.getEparchyName());
        operateSceneInstService.putExtParameter(sceneInstId, "addTransferCustInstInfo", addTransferCustInstInfo);

        // 选择了新客户后，需要将合同信息清空
        List<KiteOfferInstContract> contracts = querySceneInstService.listInsts(sceneInstId, Collections.singletonList(InstType.OFFER_INST_CONTRACT));
        if (KiteListUtils.isNotEmpty(contracts)) {
            contracts.forEach(contract -> {
                if (!KiteStringUtils.equals(contract.getActionType().name(), ActionType.X.name()) && !KiteStringUtils.equals(contract.getActionType().name(), ActionType.D.name())) {
                    operateOfferInstContractRelService.deleteOfferInstContractRel(KiteWebContext.getContext().getCurrentSceneInstId(), contract.getOfferInstId(), InstType.MAIN_OFFER_INST, contract.getOfferObjInstRelId());
                }
            });
        }
        return ErrorConsts.SUCCESS.getResult(cuccCustInfoDetailDTO);
    }

    @ApiOperation(value = "(新)查询云账户客户列表", notes = "(新)查询云账户客户列表")
    @PostMapping("/queryCustomerListNewCloud")
    public DataResult<PageInfo<CuccCustInfoDTO>> queryCustomerListNewCloud(@RequestBody KiteCustomerInfoReq kiteCustomerInfoReq) {
        if (KiteStringUtils.isEmpty(kiteCustomerInfoReq.getProvinceCode())) {
            kiteCustomerInfoReq.setProvinceCode(ContextUtil.getLoginInfo().getUserInfo().getPostProvinceNbr());
        }
        if (KiteStringUtils.isEmpty(kiteCustomerInfoReq.getEparchyCode())) {
            kiteCustomerInfoReq.setEparchyCode(ContextUtil.getLoginInfo().getUserInfo().getPostLanId());
        }
        PageInfo<CuccCustInfoDTO> list = custReceptionService.customerListQueryNewCloud(kiteCustomerInfoReq);
        return ErrorConsts.SUCCESS.getResult(list);
    }
}
